<template>
  <el-card shadow="never">
    <template #header>
      <div class="flex justify-between">
        <span class="text-sm">订单统计</span>
        <div>
          <el-check-tag v-for="(item, index) in options" :key="index" :checked="current == item.value"
            @click="handleChoose(item.value)">
            {{ item.text }}
          </el-check-tag>
        </div>
      </div>
    </template>

    <div ref="el" id="chart" style="width: 100%; height: 300px;"></div>
  </el-card>

</template>

<script setup>
//onMounted 确保在正确的时机（DOM 渲染完成后）执行依赖 DOM 的操作，避免因异步渲染导致的逻辑错误。
import { ref, onMounted,onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import {getStatistics3} from "@/api/index"
import { useResizeObserver } from '@vueuse/core'

const current = ref("week")//存储当前选中的选项值
const options = [{
  text: "近1个月",
  value: "month"
}, {
  text: "近1周",
  value: "week"
}, {
  text: "近24小时",
  value: "hour"
}]

const handleChoose = (type) => {
  current.value = type
  getDate()
}

var myChart = null
onMounted(() => {
  var chartDom = document.getElementById('chart')
  if(chartDom){
    // 节点不存在的话没必要获取数据
     myChart = echarts.init(chartDom)
      getDate()
  }
})

// 在组件销毁（切换路由、条件渲染导致组件消失）
// 会触发onBeforeUnmount，安全销毁图标，DOM元素被移除
// 即使多次切换页面，也不会让图表元素占用内存，导致应用卡顿
onBeforeUnmount(()=>{
  if(myChart) echarts.dispose(myChart)
})

function getDate(){

  let option = {
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [],
        type: 'bar'
      }
    ]
  };

  myChart.showLoading()

  getStatistics3(current.value).then(res=>{
    option.xAxis.data = res.x
    option.series[0].data = res.y

    myChart.setOption(option)
  }).finally(()=>{
    myChart.hideLoading()
  })

  

}

//监听到当整个窗口大小变化时，图表也跟着变化
const el = ref(null)
useResizeObserver(el, (entries) =>myChart.resize())
</script>